package com.example.enterprisemanager.mvvm.fragment.account.login;

import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.View;
import android.widget.Toast;

import com.example.enterprisemanager.BR;
import com.example.enterprisemanager.R;
import com.example.enterprisemanager.base.BaseBackFragment;
import com.example.enterprisemanager.base.BaseViewModel;
import com.example.enterprisemanager.databinding.FragmentLoginBinding;
import com.example.enterprisemanager.mvvm.ben.User;
import com.example.enterprisemanager.mvvm.fragment.account.register.RegisterFragment;

/**
 * Created by YoKeyword on 16/2/14.
 */
public class LoginFragment extends BaseBackFragment<FragmentLoginBinding, LoginViewModel> {

    private OnLoginSuccessListener mOnLoginSuccessListener;

    public static LoginFragment newInstance() {

        Bundle args = new Bundle();
        LoginFragment fragment = new LoginFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnLoginSuccessListener) {
            mOnLoginSuccessListener = (OnLoginSuccessListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnLoginSuccessListener");
        }
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_login;
    }

    @Override
    protected Class<LoginViewModel> getModelClass() {
        return LoginViewModel.class;
    }

    @Override
    protected int getVariableId() {
        return BR.viewModel;
    }

    @Override
    protected void initView() {
        super.initView();

        mBinding.toolbar.setTitle(R.string.login);
        initToolbarNav(mBinding.toolbar);

    }

    @Override
    protected void initData(@Nullable Bundle savedInstanceState) {

        mViewModel.sendUser.observe(this, (user) -> {
            mOnLoginSuccessListener.onLoginSuccess(user);
            pop();
        });

        mViewModel.sendToFrag.observe(this, (data) -> {
            start(RegisterFragment.newInstance());
        });
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mOnLoginSuccessListener = null;
    }

    public interface OnLoginSuccessListener {
        void onLoginSuccess(User account);
    }

    @Override
    public void onSupportInvisible() {
        super.onSupportInvisible();
        hideSoftInput();
    }
}
